package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.model.TestRecord;
import com.example.demo.service.MbtiCalculationService;
import com.example.demo.service.TestRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test-records")
public class TestRecordController {
    
    @Autowired
    private TestRecordService testRecordService;
    
    @Autowired
    private MbtiCalculationService mbtiCalculationService;

    @GetMapping("/{id}")
    public Result<TestRecord> findById(@PathVariable("id") Integer recordId) {
        return Result.success(testRecordService.findById(recordId));
    }
    
    /**
     * 根据用户ID获取测试记录列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<TestRecord>> findByUserId(@PathVariable("userId") Integer userId) {
        return Result.success(testRecordService.findByUserId(userId));
    }
    
    /**
     * 获取测试结果，包括计算的得分和类型
     */
    @GetMapping("/{id}/result")
    public Result<TestRecord> getTestResult(@PathVariable("id") Integer recordId) {
        return Result.success(testRecordService.getTestResult(recordId));
    }

    @PostMapping
    public Result<TestRecord> create(@RequestBody TestRecord testRecord) {
        // 设置默认值
        if (testRecord.getUserId() == null) {
            testRecord.setUserId(1);
        }
        if (testRecord.getTestDate() == null) {
            testRecord.setTestDate(new Date());
        }
        
        // 初始化得分为0
        testRecord.setEScore(0);
        testRecord.setIScore(0);
        testRecord.setSScore(0);
        testRecord.setNScore(0);
        testRecord.setTScore(0);
        testRecord.setFScore(0);
        testRecord.setJScore(0);
        testRecord.setPScore(0);
        testRecord.setPersonalityType("ISTJ");  // 设置一个默认值以满足外键约束
        testRecord.setIsCompleted(false);  // 新创建的测试记录默认为未完成
        
        // 创建测试记录
        TestRecord savedRecord = testRecordService.create(testRecord);
        
        return Result.success(savedRecord);
    }

    @PutMapping
    public Result<TestRecord> update(@RequestBody TestRecord testRecord) {
        return Result.success(testRecordService.update(testRecord));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable("id") Integer recordId) {
        return Result.success(testRecordService.deleteById(recordId));
    }
    
    /**
     * 提交答题结果并计算MBTI类型
     * @param recordId 测试记录ID
     * @param answers 答题选择，键为问题ID，值为选择的选项（A或B）
     * @return 更新后的测试记录
     */
    @PostMapping("/{id}/submit-answers")
    public Result<TestRecord> submitAnswers(@PathVariable("id") Integer recordId, @RequestBody Map<Integer, String> answers) {
        // 计算结果
        TestRecord calculatedResult = mbtiCalculationService.calculateResult(answers);
        
        // 获取当前测试记录
        TestRecord testRecord = testRecordService.findById(recordId);
        if (testRecord == null) {
            return Result.error("测试记录不存在");
        }
        
        // 更新测试记录的得分和类型
        testRecord.setEScore(calculatedResult.getEScore());
        testRecord.setIScore(calculatedResult.getIScore());
        testRecord.setSScore(calculatedResult.getSScore());
        testRecord.setNScore(calculatedResult.getNScore());
        testRecord.setTScore(calculatedResult.getTScore());
        testRecord.setFScore(calculatedResult.getFScore());
        testRecord.setJScore(calculatedResult.getJScore());
        testRecord.setPScore(calculatedResult.getPScore());
        testRecord.setPersonalityType(calculatedResult.getPersonalityType());
        testRecord.setIsCompleted(true);  // 标记测试为已完成
        
        // 保存更新后的测试记录
        testRecordService.update(testRecord);
        
        return Result.success(testRecord);
    }
    
    /**
     * 获取指定组织下的MBTI性格分布统计数据
     * @param orgId 组织ID，如果为null则获取全部数据
     * @param orgType 组织类型，如SCHOOL, DEPARTMENT, MAJOR, CLASS
     * @return MBTI性格分布统计数据，包含每种类型的数量和百分比
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getMbtiStatistics(
            @RequestParam(required = false) Integer orgId,
            @RequestParam(required = false) String orgType) {
        
        List<TestRecord> records = testRecordService.findCompletedRecordsByOrg(orgId, orgType);
        
        // 统计每种MBTI类型的数量
        Map<String, Integer> typeCounts = new HashMap<>();
        for (TestRecord record : records) {
            String type = record.getPersonalityType();
            typeCounts.put(type, typeCounts.getOrDefault(type, 0) + 1);
        }
        
        // 计算每种类型的百分比
        int total = records.size();
        Map<String, Double> typePercentages = new HashMap<>();
        for (Map.Entry<String, Integer> entry : typeCounts.entrySet()) {
            double percentage = total > 0 ? (entry.getValue() * 100.0 / total) : 0;
            typePercentages.put(entry.getKey(), percentage);
        }
        
        // 确保所有16种MBTI类型都有数据
        String[] allTypes = {"ISTJ", "ISFJ", "INFJ", "INTJ", "ISTP", "ISFP", "INFP", "INTP", 
                             "ESTP", "ESFP", "ENFP", "ENTP", "ESTJ", "ESFJ", "ENFJ", "ENTJ"};
        
        for (String type : allTypes) {
            if (!typeCounts.containsKey(type)) {
                typeCounts.put(type, 0);
                typePercentages.put(type, 0.0);
            }
        }
        
        // 整理返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("typeCounts", typeCounts);
        result.put("typePercentages", typePercentages);
        
        // 添加详细数据
        List<Map<String, Object>> detailedData = records.stream()
            .map(record -> {
                Map<String, Object> item = new HashMap<>();
                item.put("recordId", record.getRecordId());
                item.put("userId", record.getUserId());
                item.put("usercode", record.getUsercode());
                item.put("userFullName", record.getUserFullName());
                item.put("personalityType", record.getPersonalityType());
                item.put("testDate", record.getTestDate());
                // 添加分数信息
                item.put("eScore", record.getEScore());
                item.put("iScore", record.getIScore());
                item.put("sScore", record.getSScore());
                item.put("nScore", record.getNScore());
                item.put("tScore", record.getTScore());
                item.put("fScore", record.getFScore());
                item.put("jScore", record.getJScore());
                item.put("pScore", record.getPScore());
                // 添加组织信息
                item.put("className", record.getClassName());
                item.put("majorName", record.getMajorName());
                item.put("departmentName", record.getDepartmentName());
                return item;
            })
            .collect(Collectors.toList());
        
        result.put("detailedData", detailedData);
        
        return Result.success(result);
    }
} 